package com.matrixlearning.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.matrixlearning.mapper.SignMapper;
import com.matrixlearning.mapper.UserMapper;
import com.matrixlearning.pojo.Sign;
import com.matrixlearning.pojo.User;
import com.matrixlearning.service.UserService;
import com.matrixlearning.utils.GsonUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * Auther sun
     * DATE 2023/2/8 23:32
     * VERSION 1.0
     */
    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    SignMapper signMapper;

    @Autowired
    RedisTemplate redisTemplate;

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody String json, HttpServletResponse response) {
//        Cookie cookie = new Cookie("token", "123");
//        cookie.setMaxAge(600);
//        cookie.setPath("/");
//        response.addCookie(cookie);
        Map userMap = GsonUtils.fromJson(json, Map.class);
        String username = (String)userMap.get("username");
        String password = (String)userMap.get("password");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", password);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null) {
            return ResponseEntity.status(HttpStatus.ACCEPTED).body("error");
        }
        String token = Jwts.builder()
                .claim("id", user.getId())
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        redisTemplate.opsForValue().set("user:"+token, GsonUtils.toJson(user), Duration.ofMinutes(20));

        return ResponseEntity.ok(token);
    }

    @PostMapping("/register")
    public String register(@RequestBody String json) {
        Map userMap = GsonUtils.fromJson(json, Map.class);
        User user = new User();
        user.setUsername((String)userMap.get("username"));
        user.setPassword((String)userMap.get("password"));
        if (StringUtils.isBlank(user.getAvatar())) {
            user.setAvatar("https://img95.699pic.com/xsj/0n/3i/vr.jpg");
        } else {
            user.setAvatar((String)userMap.get("avatar"));
        }
        user.setSex((String)userMap.get("sex"));
        user.setBirth(((String)userMap.get("birth")).substring(0,10));
        String grade = (String)userMap.get("grade");
        user.setGrade(Integer.parseInt(grade.substring(5,6)));
        user.setCreatetime(format.format(new Date()));
        userMapper.insert(user);
        Sign sign = new Sign();
        sign.setFlag(0);
        sign.setNumber(0);
        signMapper.insert(sign);
        return "ok";
    }

    @PostMapping("/avatar")
    public String register(@RequestParam("avatar") MultipartFile file) {
        return "url";
    }

    @PostMapping("/getUserData")
    public String getUserData(@RequestBody String token) {
        try {
            String userJson = (String) redisTemplate.opsForValue().get("user:" + token);
            User user = GsonUtils.fromJson(userJson, User.class);
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("avatar", user.getAvatar());
            List<String> userList = new ArrayList<>();
            QueryWrapper<Sign> query =  new QueryWrapper<>();
            query.orderByDesc("number");
            query.last("limit 5");
            List<Sign> signList = signMapper.selectList(query);
            for (Sign sign:
                 signList) {
                User temp = userMapper.selectById(sign.getId());
                userList.add(temp.getUsername());
            }
            resMap.put("users", userList);
            return GsonUtils.toJson(resMap);
        } catch (Exception e) {
            return "error";
        }
    }

    @PostMapping("/userInfo")
    public String userCenter(@RequestBody String token) {
        try {
            String userJson = (String) redisTemplate.opsForValue().get("user:" + token);
            User user = GsonUtils.fromJson(userJson, User.class);
            Map<String, Object> res = new HashMap<>();
            res.put("username", user.getUsername());
            res.put("sex", user.getSex());
            res.put("grade", user.getGrade());
            //学习时间
            Instant day1 = Instant.parse(user.getCreatetime()+"T00:00:00.00Z");
            Instant now = Instant.parse(format.format(new Date()) + "T00:00:00.00Z");
            Duration duration = Duration.between(day1, now);
            res.put("learnTime", duration.toDays());
            Sign sign = signMapper.selectById(user.getId());
            res.put("signNumber", sign.getNumber());
            //年龄
            Instant birth = Instant.parse(user.getBirth()+"T00:00:00.00Z");
            Duration ageDuration = Duration.between(birth, now);
            res.put("age", ageDuration.toDays()/365);
            res.put("avatar", user.getAvatar());
            return GsonUtils.toJson(res);
        }catch (Exception e) {
            return "error";
        }
    }

    @PostMapping("/changePassword")
    public String changePassword(@RequestBody String json) {
        try {
            Map reqMap = GsonUtils.fromJson(json, Map.class);
            String passwordBefore = (String)reqMap.get("passwordBefore");
            String password = (String)reqMap.get("password");
            String password2 = (String)reqMap.get("password2");
            String token = (String) reqMap.get("token");
            String userJson = (String) redisTemplate.opsForValue().get("user:" + token);
            User user = GsonUtils.fromJson(userJson, User.class);
            if(!user.getPassword().equals(passwordBefore)) {
                return "error";
            }
            user.setPassword(password);
            userMapper.updateById(user);
            redisTemplate.opsForValue().set("user:" + token, GsonUtils.toJson(user), Duration.ofMinutes(1));
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }
}
